/**
 * Created by yananliu on 2017/10/4.
 */
import * as $ from 'jquery';
import {ApiItem} from "../constant/apis";
import {getApiWithPrefix} from "../constant/Api";
import {LayerUtil} from "./LayerUtil";

class AjaxUtil {

    public static sendRequest(name : ApiItem, param : Object,fnSuccess:Function){

        const apiJson = getApiWithPrefix(name,null);

        if(apiJson.jsonp){

            AjaxUtil.jsonpRequest(name,param);

        }else{

            AjaxUtil.normalRequest(name,param,fnSuccess);

        }

    }

    private static normalRequest(name:ApiItem,param:Object,fnSuccess:Function){

        const apiJson = getApiWithPrefix(name,null);

        $.ajax({
            url: apiJson.url,
            type: apiJson.type,
            data: apiJson.header === 'json' ? ($.isEmptyObject(param) ? {} : JSON.stringify(param)) : param,
            cache : false,
            dataType: "JSON",
            async : apiJson.async,
            contentType:apiJson.header === 'json' ? "application/json; charset=utf-8" : "application/x-www-form-urlencoded;charset=UTF-8",
            success : function(res : any){

                fnSuccess && fnSuccess(res);

                if(name.url.indexOf('ajaxPay') !== -1){
                    //余额支付有自己的逻辑
                    return;
                }

                if(res.code !== 0) {

                    if (res.msg) {
                        LayerUtil.toast(res.msg);
                    } else {
                        LayerUtil.toast(JSON.stringify(res));
                    }
                }
            }
        });
    }

    private static jsonpRequest (name:ApiItem,param:Object){

        const apiJson = getApiWithPrefix(name,null);

        console.log(apiJson);

        $.ajax({
            url: apiJson.url,
            type: 'GET',
            data: param,
            cache : false,
            async : apiJson.async,
            dataType: "jsonp",
            success : function(res){
                if(res.code === 0){
                    window.location.href = "http://u.caixin.com/user/uc/logout.html?url=" + encodeURIComponent(window.location.href);
                }else{
                    window.location.reload();
                }
            }
        });

    }
}

export default AjaxUtil;